import { createRouter, createWebHashHistory } from 'vue-router'
// 🔔 注意：这里需要引入 store 实例
import store from '@/store/index'

const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home/index')
const TopCategory = () => import('@/views/category/index')
const SubCategory = () => import('@/views/category/sub.vue')
const Goods = () => import('@/views/goods/index.vue')
const Login = () => import('@/views/login/index.vue')
const LoginCallback = () => import('@/views/login/callback.vue')
const Cart = () => import('@/views/cart/index.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: 'category/:id', component: TopCategory },
      { path: 'category/sub/:id', component: SubCategory },
      { path: 'product/:id', component: Goods },
      { path: 'cart', component: Cart }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  { path: '/login/callback', component: LoginCallback }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior () {
    // 滚动平滑
    return { top: 0, behavior: 'smooth' }
  }
})

router.beforeEach((to, from, next) => {
//  获取用户token
  const { token } = store.state.user.profile
  // 如果用户没有 token，但是想访问 /member 开头的路由，需要跳转到登录页，并携带会跳地址
  if (!token && to.path.startsWith('/member')) {
    next(`/login?redirectUrl=${to.fullPath}`)
  }
  next()
})
export default router
